package com.chenyun.system.feign;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.chenyun.system.model.SysRole;
import com.chenyun.system.model.SysUser;
import com.chenyun.system.param.SysUserQueryPage;
import com.chenyun.system.service.ISysMenuService;
import com.chenyun.system.service.ISysUserService;
import com.chenyun.common.enums.LoginDeviceTypeEnum;
import com.chenyun.common.enums.LoginUserTypeEnum;
import com.chenyun.common.utils.StringUtils;
import com.chenyun.common.vo.PageResult;
import com.chenyun.common.vo.ServiceResponse;
import com.chenyun.common.vo.SessionUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 平台|商家后台用户远程调用实现类
 *
 * @author: Lonni
 * @date: 2023/3/29 0029 9:40
 */
@RestController
@ApiIgnore
@Slf4j
public class SysUserClient implements ISysUserFeign {

    @Autowired
    private ISysUserService userService;

    @Autowired
    @Lazy
    private ISysMenuService menuService;





    /**
     * 分压查询商户管理员
     *
     * @param page
     * @return
     */
    @Override
    public PageResult listMerchantUserPage(SysUserQueryPage page) {
        if (StringUtils.isBlank(page.getMerchantId())) {
            return PageResult.FAIL("商户编号必须传入!");
        }
        page.setUserType("1");
        PageResult result = userService.selectUserListPage(page);
        return result;
    }

    /**
     * 添加平台用户
     *
     * @param merchantUser
     * @return
     */
    @Override
    public ServiceResponse addMerchantUser(SysUser merchantUser) {
        if (StringUtils.isBlank(merchantUser.getMerchantId())) {
            return ServiceResponse.fail("商户编号必填!");
        }
        merchantUser.setUserType("1");
        userService.insertUser(merchantUser);
        return ServiceResponse.success();
    }

    /**
     * 修改平台用户
     *
     * @param merchantUser
     * @return
     */
    @Override
    public ServiceResponse editMerchantUser(SysUser merchantUser) {
        if (StringUtils.isBlank(merchantUser.getMerchantId())) {
            return ServiceResponse.fail("商户编号必填!");
        }
        merchantUser.setUserType("1");
        userService.updateUser(merchantUser);
        return ServiceResponse.success();
    }

    /**
     * 删除平台用户
     *
     * @param ids
     * @return
     */
    @Override
    public ServiceResponse delMerchantUser(List<String> ids) {
        Long[] longs = ids.stream().map(Long::valueOf).collect(Collectors.toList()).toArray(new Long[]{});
        userService.deleteUserByIds(longs);
        return ServiceResponse.success();
    }


    /**
     * 查询平台后台用户
     *
     * @param param
     * @return
     */
    @Override
    public ServiceResponse<SessionUser>  findPlatFormUser(Map<String, String> param) {
        SessionUser userHandler = findUserHandler(param, false);
        return ServiceResponse.success(userHandler);
    }

    /**
     * 查询商户后台用户
     *
     * @param param 必须包含merchantId
     * @return
     */
    @Override
    public ServiceResponse<SessionUser> findMerchantUser(Map<String, String> param) {
        SessionUser userHandler = findUserHandler(param, true);
        return ServiceResponse.success(userHandler);
    }


    SessionUser findUserHandler(Map<String, String> param, boolean isMerchant) {
        String username = param.get("username");
        String userType = param.get("userType");
        String deviceType = param.get("deviceType");
        String phone = param.get("phone");
        String encryptedData = param.get("encryptedData");
        String iv = param.get("iv");
        SysUser user = null;
        Set<String> menuPer = new HashSet<>();
        if (StringUtils.isNotBlank(phone)) {
            SysUser qUser = new SysUser();
            qUser.setPhonenumber(phone);
            qUser.setUserType(isMerchant ? "1" : "0");
            List<SysUser> sysUsers = userService.selectUserList(qUser);
            if (CollectionUtil.isNotEmpty(sysUsers)) {
                user = sysUsers.get(0);
            }

        } else if (StringUtils.isNotBlank(encryptedData) && StringUtils.isNotBlank(iv)) {
        } else {
            SysUser qUser = new SysUser();
            qUser.setUserName(username);
            qUser.setUserType(isMerchant ? "1" : "0");
            List<SysUser> sysUsers = userService.selectUserList(qUser);
            if (CollectionUtil.isNotEmpty(sysUsers)) {
                user = sysUsers.get(0);
            }
        }
        if (user == null) {
            return null;
        }
        menuPer=  menuService.selectMenuPermsByUserId(Long.valueOf(user.getUserId()));
        SessionUser sessionUser = SessionUser.builder()
                .userId(user.getUserId())
                .deptId(Objects.toString(user.getDeptId()))
                .userName(user.getUserName())
                .nickName(user.getNickName())
                .deviceType(LoginDeviceTypeEnum.valueOf(deviceType))
                .userType(LoginUserTypeEnum.valueOf(userType))
                .openId(user.getOpenId())
                .unionId(user.getUnionId())
                .phone(user.getPhonenumber())
                .password(user.getPassword())
                .shopId(isMerchant ? user.getMerchantId() : "")
                .shopName("")
                .build();

        log.info("user.getRoles():{}", JSON.toJSONString(user));
        sessionUser.setRolePermission(user.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toSet()));
        //赋值权限
        sessionUser.setMenuPermission(menuPer);
        return sessionUser;
    }







}



